# https://www.jianshu.com/p/8d1bdd7f4ff5
from peewee import *
from config.database import *
from datetime import *

print(CHARSET)

# 连接mysql
db = MySQLDatabase(charset=CHARSET, user=USERNAME, password=PASSWORD, database=DATABASE, host=HOST, port=PORT)

class Person(Model):
    name = CharField()
    birthday = DateField()
    is_relative = BooleanField()

    class Meta:
        database = db
        # table_name = 's_person'

# 创建表
Person.create_table()

# 创建表也可以这样, 可以创建多个.gitignore
# database.create_tables([Person])

# 添加一条数据
# p = Person(name='liuchungui', birthday=date(1990, 12, 20), is_relative=True)
# p.save()

# 查询单条数据
p = Person.get(Person.name == 'liuchungui')
print(p.id, p.name, p.birthday, p.is_relative)

# 原生sql
# p = db.execute_sql('select * from person').fetchone()
p = db.execute_sql('select * from person').fetchall()
print(p)

# 使用where().get()查询
# p = Person.select().where(Person.name == 'liuchungui').get()
# print(p.name, p.birthday, p.is_relative)

# 查询多条数据
# persons = Person.select().where(Person.is_relative == True)
# for p in persons:
#     print(p.name, p.birthday, p.is_relative)

# 删除姓名为perter的数据
# Person.delete().where(Person.name == 'perter').execute()

# 已经实例化的数据, 使用delete_instance
# p = Person(name='liuchungui', birthday=date(1990, 12, 20), is_relative=False)
# p.id = 1
# p.save()
# p.delete_instance()


# 已经实例化的数据,指定了id这个primary key,则此时保存就是更新数据
# p = Person(name='liuchungui', birthday=date(1990, 12, 20), is_relative=False)
# p.id = 1
# p.save()

# 更新birthday数据
# q = Person.update({Person.birthday: date(1983, 12, 21)}).where(Person.name == 'liuchungui')
# q.execute()